#!/root/venv/bin/python3.5
from flask import Flask,render_template,request
import subprocess as s
import  pymysql

app = Flask(__name__)


'''@app.route('/')
def index():
    return "welcome to wolan_ali devops system!"'''
def dbopt(sql):
    db = pymysql.connect(host='wolan6',user='remote', password='123456',port=3306, charset='utf8')
    cursor = db.cursor()
    cursor.execute(sql)
    db.close()
    return dict(cursor.fetchall())
def dbinsert(sql):
    db = pymysql.connect(host='wolan6', user='remote', password='123456', port=3306, charset='utf8')
    cursor = db.cursor()
    cursor.execute(sql)
    db.commit()
    db.close()
@app.route('/clearmac', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        if request.form.get('passwd')=='zjb1990':
            #return '{} '.format(request.form.get('fname'))
            phonenum = request.form.get('fname')
            s.os.chdir('/root/shell')
            s.os.system('bash /root/shell/clearphone.sh {}'.format(phonenum))
            error  = '{}解绑成功'.format(phonenum)
            return render_template('index.html', error=error)
        else:
            error = '执行密码错误'
            return render_template('index.html', error=error)
    return render_template('index.html', error=error)
        #if request.form['username'] == 'abc' and request.form['password'] == '123':
       #     return request.form['username']
       # else:
        #    error = 'Invalid username/password'

@app.route('/addphone', methods=['GET', 'POST'])
def addphone():
    sql = 'select c.name,c.id from db_wo.t_channel c where c.name  like "%主路由" order by c.level,c.id; '
    data = dbopt(sql)
    error = None
    if request.method == 'POST':
        error = None
        arg1 = request.form.get('fname')
        arg2 = request.form.get('siteid', False)
        sql = "INSERT INTO openportal.portal_account VALUES (REPLACE(UUID(),'-',''), '{}', 'e10adc3949ba59abbe56e057f20f883e', NULL, NULL, now(), now(), 0, '1', 1, 1, 0, NULL,'{}','','0');".format( arg1, arg2)
        if not arg2:
            arg2 = 'NULL'
            sql = "INSERT INTO openportal.portal_account VALUES (REPLACE(UUID(),'-',''), '{}', 'e10adc3949ba59abbe56e057f20f883e', NULL, NULL, now(), now(), 0, '1', 1, 1, 0,NULL, {},'','0');".format(arg1, arg2)
        try:
            dbinsert(sql)
            error = '手机号码{}添加白名单成功'.format(arg1)
        except  Exception as err:
            err = str(err)
            if  'Duplicate' in  err:
                error =  '手机号码{}已在白名单中'.format(arg1)
            else:
                error = err
        return render_template('addphone.html', error=error,data=data)

    # data = {'沈砖公路江秋路（天文台）': '62', '佘山四合一工地': '49', '嘉定宝塔路温泉路（盘古天地）主路由': '71', '虹口演示渠道': '41', }
    return render_template('addphone.html', data=data)
if __name__ == '__main__':
    app.run(host='0.0.0.0',port=5500)
